#include "mainwindow.h"
#include "ui_mainwindow.h"


#include "stdio.h"
#include "stdlib.h"

#include <string>
using namespace std;


int g_packgeHeadSize = 8;
int g_packgeDataSize = 128;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_m_butRun_clicked()
{
    QString strIn("/home/sdb/test.bin");
    QString strOut("/home/sdb/test.hex");

    string szIn = strIn.toStdString();
    string szOut = strOut.toStdString();


    FILE *fpR = fopen( szIn.c_str(), "rb" );
    if( fpR != NULL)
    {

        FILE *fpW = fopen( szOut.c_str(), "wt" );
        if( fpW != NULL )
        {
            int iFileSize = 0;
            fseek( fpR, 0, SEEK_END );
            iFileSize = ftell( fpR );
            fseek( fpR, 0, SEEK_SET );

            int cntLine = iFileSize / g_packgeDataSize;
            if( iFileSize % g_packgeDataSize != 0 )
                cntLine += 1;

            int packgeSize = g_packgeHeadSize + g_packgeDataSize;
            unsigned char *pBuff = new unsigned char[ packgeSize  ];
            ////
            if( pBuff != NULL )
            {
                int i = 0, j = 0;
                int iR = 0;

                fprintf(fpW, "unsigned char g_pBuff[] = {\n");
                /// write lines
                for( i=0; i<cntLine-1; i++ )
                {
                    iR = fread( pBuff + g_packgeHeadSize, 1, g_packgeDataSize, fpR );
                    // fill head


                    // fill data
                    fprintf( fpW, "\t" );
                    for( j=0; j< packgeSize; j++)
                    {
                        if( j%8 == 0)
                            fprintf( fpW, " 0x%x,", pBuff[j] );
                        else
                            fprintf( fpW, "0x%x,", pBuff[j] );
                    }

                    fprintf( fpW, "\n" );
                }

                /// write last line
                iR = fread( pBuff + g_packgeHeadSize, 1, g_packgeDataSize, fpR );
                // fill head

                fprintf( fpW, "\t" );
                for( j=0; j< packgeSize-1; j++)
                {
                    if( j%8 == 0)
                        fprintf( fpW, " 0x%x,", pBuff[j] );
                    else
                        fprintf( fpW, "0x%x,", pBuff[j] );
                }

                fprintf( fpW, "0x%x\n};\n", pBuff[j] );

                ///
                delete []pBuff;
            }
            ///
            fclose( fpW );
        }
        ///
        fclose( fpR );
    }

}
